#include "enroll.h"
#include "ui_enroll.h"

#include <QFile>


Enroll::Enroll(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Enroll)
{
    ui->setupUi(this);
    ui->edit_userId->setValidator(new QIntValidator(ui->edit_userId));
    //加载样式表
    QString styleSheetFile = ":/new/prefix2/StyleSheet/enrollStyle.qss";
    QFile file(styleSheetFile);
    file.open(QFile::ReadOnly);
    if (file.isOpen())
    {
        QString styleSheet = this->styleSheet();
        styleSheet += QLatin1String(file.readAll());//读取样式表文件
        this->setStyleSheet(styleSheet);
        file.close();
    }
//    else
//    {
//        QMessageBox::information(this,"tip","cannot find qss file");
//    }

}

Enroll::~Enroll()
{
    delete ui;
}

void Enroll::on_btn_return_clicked()
{
    this->hide();
}

//注册账号，用户名（ID）为唯一标志
void Enroll::on_btn_ok_clicked()
{
    userInfo temp;
    //判断是否为空
    if(ui->edit_userId->text().isEmpty() || ui->edit_password->text().isEmpty())
    {
         QMessageBox::information(nullptr, "infor", "请填写完整！");
    }
    else
    {
        //获取输入信息
        int user_id = ui->edit_userId->text().toInt();
        QString user_password = ui->edit_password->text();
        temp.id = user_id;
        temp.password = user_password;

        if(isInsert(temp))
        {
            QMessageBox::information(nullptr, "infor", "注册成功！");
            this->hide();
        }
        else
        {
            QMessageBox::information(nullptr, "infor", "用户名已存在！");
            //清空输入框
            ui->edit_userId->clear();
            ui->edit_password->clear();
        }
    }

}
//插入账号
bool Enroll::isInsert(userInfo user)
{
    QSqlQuery query;
    //将密码使用md5转换后储存
    QString md5_password = QCryptographicHash::hash(user.password.toLatin1(),QCryptographicHash::Md5).toHex();
    return query.exec(QString("insert into users values(%1, '%2');").arg(user.id).arg(md5_password));
}

